﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;

namespace EmuladorSMS
{
    class ConexaoSerial
    {
        private static ConexaoSerial instance;
        SerialPort port;
        private ConexaoSerial()
        {

        }

        public static ConexaoSerial Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new ConexaoSerial();
                }
                return instance;
            }
        }

        public void abrirPorta(string porta,int baudRate)
        {
            port = new SerialPort(porta, baudRate, Parity.None, 8, StopBits.One);
            try
            {
                port.Open();
                Console.WriteLine("###### Conectado ######");
                Console.WriteLine("Porta: " + porta);
                Console.WriteLine("Velocidade: " + baudRate);
                Console.WriteLine("Parity.None");
                Console.WriteLine("Bits: 8");
                Console.WriteLine("StopBits.One");
            }
            catch (Exception e) { throw e; }
        }

        public void enviarStringPorta(string texto)
        {
            if (port != null && port.IsOpen)
            {
                port.Write(texto);
            }
            else
            {
                throw new NotOpenConexaoException();
            }
        }

        public string obterStringPorta()
        {
            string retorno = "";
            try
            {
                if (port.IsOpen)
                {
                    //retorno = port.ReadLine();
                    retorno = port.ReadExisting();
                }
            }
            catch (InvalidOperationException e)
            {
                Console.WriteLine(e.Message);
            }
            catch (TimeoutException e)
            {
                Console.WriteLine(e.Message);
            }
            return retorno;
        }

        public void fecharPorta()
        {
            if (port.IsOpen)
            {
                port.Close();
            }
            else
            {
                throw new NotOpenConexaoException();
            }
        }

        public Boolean isOpen()
        {
            if (port == null)
                return false;
            else
                return port.IsOpen;
        }
    }

    
}
